package com.novellotus.iov.carvice.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.alipay.AlipayModel;
import com.novellotus.iov.carvice.bean.WXPayBean;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.utils.DataSign;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

public class ConfirmPayActivity extends BaseActivity {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.img_cwx)
    ImageView img_cwx;
    @BindView(R.id.img_cali)
    ImageView img_cali;
    AlipayModel aliPay;

    boolean isAlipay = true;
    private IWXAPI api;


    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_confirm_pay);
    }

    @Override
    public void init() {
        tv_tittle.setText("确认支付");
        aliPay = new AlipayModel();
        api = WXAPIFactory.createWXAPI(this, "wx27932ca8a5af2b66");

    }

    @OnClick(R.id.img_back)
    void back() {
        finish();
    }


    @OnClick(R.id.rlt_weixin)
    void chooseWX() {
        isAlipay = false;
        img_cwx.setImageResource(R.mipmap.icon_pay_choose);
        img_cali.setImageResource(R.mipmap.icon_pay_not_choose);
    }

    @OnClick(R.id.rlt_zfb)
    void chooseZFB() {
        isAlipay = true;
        img_cwx.setImageResource(R.mipmap.icon_pay_not_choose);
        img_cali.setImageResource(R.mipmap.icon_pay_choose);
    }


    @OnClick(R.id.btn_pay)
    void pay() {

        if (isAlipay) {
            // aliPay.aliPay(this);
            getAliPay();
        } else {
            wxPay();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MyUtils.logInformation("微信支付完成回到梦开始的地方");
        if (data != null) {
            switch (data.getIntExtra("code", 0)) {
                case 0:
                    MyUtils.showToast(this, "支付成功");
                    MyUtils.addActivity(this);
                    openActivity(PaySuccessActivity.class);
                    break;
                case -1:
                    MyUtils.showToast(this, "支付失败");
                    break;
                case -2:
                    MyUtils.showToast(this, "支付取消");
                    break;
            }

        }
    }

    private void wxPay() {
        MyUtils.showToast(this, "正在获取微信订单信息");
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("body", "歼10战斗机");
            requestData.put("amount", "0.01");
            requestData.put("orderNo", "");
            requestData.put("access_token", SharedPreferencesUtils.getKey(this)[0]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Observable<BaseEntity<WXPayBean>> observable = RetrofitFactory.getInstance().getWXOrderpay(DataSign.getSign(requestData.toString(), this));
        observable.compose(RxSchedulers.<BaseEntity<WXPayBean>>compose())
                .subscribe(new BaseObserver<WXPayBean>(this) {

                    @Override
                    public void onSuccess(WXPayBean orderInfo) {
                        payDeal(orderInfo);
                    }

                    @Override
                    public void onFail(int code, String msg) {

                    }

                    @Override
                    public void onError(String msg) {
                    }
                });
    }

    private void payDeal(WXPayBean result) {
        PayReq req = new PayReq();
        req.appId = result.getAppid();
        req.partnerId = result.getPartnerid();
        req.prepayId = result.getPrepayid();
        req.nonceStr = result.getNoncestr();
        req.timeStamp = result.getTimestamp();
        req.packageValue = result.getPackageX();
        req.sign = result.getSign();
        //  req.extData = "app data"; // optional
        MyUtils.showToast(this, "正在调起微信支付");
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        api.sendReq(req);
    }


    /**
     * 获取支付宝订单
     */
    public void getAliPay() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("body", "歼10");
            requestData.put("amount", "0.01");
            requestData.put("orderNo", "");
            requestData.put("access_token", SharedPreferencesUtils.getKey(this)[0]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Observable<BaseEntity<String>> observable = RetrofitFactory.getInstance().getAliOrderpay(DataSign.getSign(requestData.toString(), this));
        observable.compose(RxSchedulers.<BaseEntity<String>>compose())
                .subscribe(new BaseObserver<String>(this) {

                    @Override
                    public void onSuccess(String orderInfo) {
                        aliPay.aliPay(ConfirmPayActivity.this, orderInfo);
                    }

                    @Override
                    public void onFail(int code, String msg) {

                    }

                    @Override
                    public void onError(String msg) {
                    }
                });
    }
}
